package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.constant.CodeEnum;
import org.example.exception.ServiceException;
import org.example.mapper.ArticleMapper;
import org.example.model.Article;
import org.example.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    
    @Override
    @Transactional
    public Article createArticle(Article article) {
        // 数据校验
        validateArticle(article);
        
        // 设置为已发布状态
        article.setStatus("published");
        article.setPublishTime(LocalDateTime.now());
        article.setViewCount(0); // 初始化阅读数为0
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        
        // 保存文章
        save(article);
        return article;
    }
    
    @Override
    @Transactional
    public Article saveDraft(Article article) {
        // 数据校验 - 草稿可以不需要完整内容
        if (article.getTitle() == null || article.getTitle().trim().isEmpty()) {
            throw new ServiceException(CodeEnum.FAIL.getCode(), "文章标题不能为空");
        }
        
        // 设置为草稿状态
        article.setStatus("draft");
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        
        // 保存文章
        save(article);
        return article;
    }
    
    @Override
    public List<Article> getArticleList() {
        // 按发布时间倒序查询，只查询已发布的文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, "published")
                .orderByDesc(Article::getPublishTime);
        
        return list(queryWrapper);
    }
    
    /**
     * 获取所有文章，包括草稿
     */
    @Override
    public List<Article> getAllArticles() {
        // 按更新时间倒序查询所有文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getUpdateTime);
        
        return list(queryWrapper);
    }
    
    /**
     * 获取草稿列表
     */
    @Override
    public List<Article> getDrafts() {
        // 按更新时间倒序查询草稿
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, "draft")
                .orderByDesc(Article::getUpdateTime);
        
        return list(queryWrapper);
    }
    
    @Override
    public Article getArticleById(Long id) {
        Article article = getById(id);
        if (article == null) {
            throw new ServiceException(CodeEnum.ERROR.getCode(), "文章不存在");
        }
        
        // 如果是已发布的文章，增加阅读数
        if ("published".equals(article.getStatus())) {
            article.setViewCount(article.getViewCount() + 1);
            article.setUpdateTime(LocalDateTime.now()); // 更新修改时间
            updateById(article);
        }
        
        return article;
    }
    
    @Override
    @Transactional
    public Article updateArticle(Article article) {
        // 验证文章ID
        if (article.getId() == null) {
            throw new ServiceException(CodeEnum.FAIL.getCode(), "文章ID不能为空");
        }
        
        Article existingArticle = getById(article.getId());
        if (existingArticle == null) {
            throw new ServiceException(CodeEnum.ERROR.getCode(), "文章不存在");
        }
        
        // 如果是发布文章，需要进行数据校验
        if ("published".equals(article.getStatus())) {
            validateArticle(article);
        }
        
        // 如果原来是草稿，现在是发布状态，需设置发布时间
        if ("draft".equals(existingArticle.getStatus()) && "published".equals(article.getStatus())) {
            article.setPublishTime(LocalDateTime.now());
        }
        
        // 设置更新时间，保留原创建时间
        article.setUpdateTime(LocalDateTime.now());
        article.setCreateTime(existingArticle.getCreateTime());
        
        // 保留原阅读数，除非明确设置了新的阅读数
        if (article.getViewCount() == null) {
            article.setViewCount(existingArticle.getViewCount());
        }
        
        updateById(article);
        return article;
    }
    
    @Override
    @Transactional
    public void deleteArticle(Long id) {
        Article article = getById(id);
        if (article == null) {
            throw new ServiceException(CodeEnum.ERROR.getCode(), "文章不存在");
        }
        
        // 删除文章封面图片（如果有）
        if (StringUtils.hasText(article.getCoverImage())) {
            // 这里可以添加图片文件删除逻辑
            // 但需要注意图片可能被多篇文章引用，应该谨慎删除
            // 更好的做法是引入图片资源管理和引用计数
        }
        
        removeById(id);
    }
    
    /**
     * 验证文章数据
     */
    private void validateArticle(Article article) {
        if (article.getTitle() == null || article.getTitle().trim().isEmpty()) {
            throw new ServiceException(CodeEnum.FAIL.getCode(), "文章标题不能为空");
        }
        
        if (article.getContent() == null || article.getContent().trim().isEmpty()) {
            throw new ServiceException(CodeEnum.FAIL.getCode(), "文章内容不能为空");
        }
        
        // 标题长度限制
        if (article.getTitle().length() > 100) {
            throw new ServiceException(CodeEnum.FAIL.getCode(), "文章标题不能超过100个字符");
        }
    }
} 